package com.ssyc.student.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.MathUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.student.R;
import com.ssyc.student.bean.CloneWordPrepareInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.iflytek.Result;
import com.ssyc.student.iflytek.XmlResultParser;
import com.tencent.taisdk.TAIError;
import com.tencent.taisdk.TAIOralEvaluation;
import com.tencent.taisdk.TAIOralEvaluationCallback;
import com.tencent.taisdk.TAIOralEvaluationData;
import com.tencent.taisdk.TAIOralEvaluationEvalMode;
import com.tencent.taisdk.TAIOralEvaluationFileType;
import com.tencent.taisdk.TAIOralEvaluationListener;
import com.tencent.taisdk.TAIOralEvaluationParam;
import com.tencent.taisdk.TAIOralEvaluationRet;
import com.tencent.taisdk.TAIOralEvaluationServerType;
import com.tencent.taisdk.TAIOralEvaluationStorageMode;
import com.tencent.taisdk.TAIOralEvaluationTextMode;
import com.tencent.taisdk.TAIOralEvaluationWord;
import com.tencent.taisdk.TAIOralEvaluationWorkMode;
import com.tencent.taisdk.TAIRecorderParam;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;

/**
 * 学生端--词汇预习界面--语音评测的界面
 * Created by Administrator on 2018/5/11 0011.
 */

public class StudentVocabularyPrepareThirdActivity extends BaseActivity implements View.OnClickListener {


    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    //GradeId
    private String gradeId;


    //返回
    private ImageView ivBack;

    //收藏的整体布局
    private RelativeLayout rlCollection;

    //收藏的图标
    private ImageView ivCollection;

    //进度条
    private ZzHorizontalProgressBar pb;
    //显示进度条的进度
    private TextView tvPb;
    //播放单词录音
    private ImageView ivPlayWord;
    //单词的内容
    private TextView tvWordName;
    //音标
    private TextView tvWordPhonetic;

    //单词的中文解释
    private TextView tvWordExplan;
    //展示单词图片
    private ImageView ivPic;
    //播放句子录音
    private ImageView ivPlaySentence;

    //句子的内容
    private TextView tvSentenceName;
    //句子的中文解释
    private TextView tvSentenceExplan;
    //播放录制音频
    private ImageView ivPlayRecord;
    //录制音频
    private ImageView ivRecord;
    //显示评分的TextView
    private TextView tvScore;
    //正在评分的Loading布局
    private LinearLayout llLoading;
    //继续按钮
    private Button btNext;

    //外层视图
    private RelativeLayout rlMain;

    //所有条目数据的集合,需要将这个值传递个下个界面
    private List<CloneWordPrepareInfo.DataBean.QuestionListBean> data;

    //当前页面条目的位置,这个位置的值需要+1后传递给下个页面
    private int currPos;

    //当前页面条目的对象
    private CloneWordPrepareInfo.DataBean.QuestionListBean info;

    //单词的帧动画对象
    AnimationDrawable wordAnim;

    //句子的帧动画对象
    AnimationDrawable senceAnim;

    //记录按下的时间
    private long downTime;

    //记录松手的时间
    private long upTime;


    //录音对象
    private MediaRecorder mediaRecorder;


    /**
     * 录音的弹框PopUpWinow相关
     */
    private View view;
    private ImageView lvPopRecord;
    private PopupWindow popupWindow;
    //录音对话框的帧动画对象
    private AnimationDrawable popAnimationDrawable;

    // 讯飞SDK对象
    private SpeechEvaluator mSpeechEvaluator;


    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_vocabulary_prepare_third;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //初始化录制音频按钮的触摸事件
        initRecrdTouchEvent();

        //获取传递的页面数据
        initData();

        //配置科大讯飞的参数
        setParams();


        //配置腾讯云语音评测对象的参数
//        setTencentParams();

        //设置进度条的数据
        initPbData();

        //设置页面其它数据的方法
        setPageData();

    }

    /**
     * 初始化视图的方法
     */
    public void initView() {
        rlMain = findViewById(R.id.rl_main);
        ivBack = findViewById(R.id.iv_back);
        rlCollection = findViewById(R.id.rl_collection);
        rlCollection.setOnClickListener(this);
        ivCollection = findViewById(R.id.iv_collection);
        ivBack.setOnClickListener(this);
        pb = findViewById(R.id.pb);
        tvPb = findViewById(R.id.tv_pb);
        ivPlayWord = findViewById(R.id.iv_play_word);
        ivPlayWord.setOnClickListener(this);
        tvWordName = findViewById(R.id.tv_word_name);
        tvWordPhonetic = findViewById(R.id.tv_word_phonetic);
        tvWordExplan = findViewById(R.id.tv_word_explan);
        ivPic = findViewById(R.id.iv_pic);
        ivPlaySentence = findViewById(R.id.iv_play_sentence);
        ivPlaySentence.setOnClickListener(this);
        tvSentenceName = findViewById(R.id.tv_sentence_name);
        tvSentenceExplan = findViewById(R.id.tv_sentence_explan);
        ivPlayRecord = findViewById(R.id.iv_play_record);
        ivPlayRecord.setOnClickListener(this);
        ivRecord = findViewById(R.id.iv_record);
        tvScore = findViewById(R.id.tv_score);
        llLoading = findViewById(R.id.ll_loading);
        llLoading.setVisibility(View.INVISIBLE);
        tvScore.setVisibility(View.INVISIBLE);
        btNext = findViewById(R.id.bt_next);
        btNext.setOnClickListener(this);
    }


    /**
     * 原生录音开始
     */
    private void startMediaRecord() {
        if (mediaRecorder != null) {
            mediaRecorder = null;
        }

        // 获取内部存储目录
//        File directory = context.getFilesDir();
//        File directory = getExternalCacheDir();

//        File directory = getExternalFilesDir(null);
        File directory = getCacheDir();
        String fileName = "app_record_" +
                +currPos
                + ".mp3";

        // 创建文件对象
        File file = new File(directory, fileName);
        try {
            // 如果文件不存在，则创建它
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//        String filePath = getExternalCacheDir().getAbsolutePath() + "app_record_" +
//                +currPos
//                + ".mp3";

        mediaRecorder = new MediaRecorder();
        //设置音频源为麦克风
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //设置音频格式
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        //设置音频编码方式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setOutputFile(file.getAbsolutePath());
//        mediaRecorder.setOutputFile(filePath);
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (IOException e) {
            LogUtils.iTag("test", e);
            e.printStackTrace();
        }
    }

    /**
     * 停止原生录音
     */
    private void stopMediaRecord() {
        try {
//            LogUtils.iTag("test", "----------" + mediaRecorder);
            mediaRecorder.stop();
            mediaRecorder.release();
        } catch (Error e) {
            LogUtils.iTag("test", e);
        }

    }


    /**
     * 初始化数据
     */
    private void initData() {

        //获取传递过来的LessonId和gradeId
        lessonId = getIntent().getStringExtra(LESSONID);
        gradeId = getIntent().getStringExtra(GRADEID);

        //获取所有条目的数据
        data = GsonUtil.jsonToList(getIntent().getStringExtra("questioninfos"), CloneWordPrepareInfo.DataBean.QuestionListBean[].class);

        //获取当前位置
        currPos = getIntent().getIntExtra("currpos", -1);

        //得到当前页面条目的对象
        info = data.get(currPos);

        //初始化收藏的默认图标
        if (info.getCollection() == 0) {
            ivCollection.setImageResource(R.drawable.st_collection_normal);
        } else if (info.getCollection() == 1) {
            ivCollection.setImageResource(R.drawable.st_collection_has_select);
        }
    }


    /**
     * 初始化录制音频按钮的触摸事件
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initRecrdTouchEvent() {
        ivRecord.setOnTouchListener(new View.OnTouchListener() {

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        //判断是否有录音权限,如果有进行弹框录音,如果没有,则申请录音权限


                        if (hasRecordPermission()) {

                            //开启录制音频
                            startRecord();

                            //开始原生录制
//                            startMediaRecord();

                        } else {
                            //没有权限,申请录音权限
                            ActivityCompat.requestPermissions(StudentVocabularyPrepareThirdActivity.this, new String[]{
                                    android.Manifest.permission.RECORD_AUDIO}, 1);
                        }
                        break;

                    case MotionEvent.ACTION_UP:

                        // LogUtils.iTag("test","响应抬起事件了"+hasRecordPermission());
                        if (hasRecordPermission()) {
                            //有权限在执行响应的操作
                            //记录松开手的时间
                            upTime = System.currentTimeMillis();

                            if (upTime - downTime > 800) {

                                //停止录音并且开始测评
                                if (null != oral && oral.isRecording()) {

                                    //腾讯智聆口语评测老版本
                                    oral.stopRecordAndEvaluation(new TAIOralEvaluationCallback() {
                                        @Override
                                        public void onResult(TAIError error) {
                                        }
                                    });

                                    //科大讯飞的停止评测的方法
                                    mSpeechEvaluator.stopEvaluating();

//                                    腾讯智聆口语评测新版
//                                oral.stopRecordAndEvaluation();

                                    //停止原生录音-腾讯云的评测需要结合原生录音一起使用
//                                   stopMediaRecord();
                                }

                                // 松手的时候开始加载框转圈功能
                                llLoading.setVisibility(View.VISIBLE);

                            }

                            // 松下的操作
                            if (null != popupWindow && popupWindow.isShowing()) {
                                popupWindow.dismiss();
                            }
                        }
                        break;
                }

                return true;
            }
        });
    }


    /**
     * 判断是否有录音权限
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private Boolean hasRecordPermission() {
        return PermissionUtils.isGranted(Manifest.permission.RECORD_AUDIO);
    }


    /**
     * 开启录制音频
     */
    private void startRecord() {

        downTime = System.currentTimeMillis();

        // 隐藏加载显示分数,下一步按钮
        llLoading.setVisibility(View.INVISIBLE);
        tvScore.setVisibility(View.INVISIBLE);

        // 按下的操作
        showRecordPop();

        //开始科大讯飞的录音并设置监听
        doRecordAction();

        //开始腾讯云的录音并设置评测监听
//        doTencenRecordAction();
    }


    /**
     * 设置进度条的数据
     */
    private void initPbData() {
        //进度条的进度
        pb.setProgress((int) (MathUtil.deciMal((currPos + 1), data.size()) * 100));
        //显示进度的文字
        tvPb.setText((currPos + 1) + "/" + data.size());
    }


    /**
     * 设置页面数据的方法
     */
    private void setPageData() {
        //设置单词名称
        tvWordName.setText(info.getWordname());
        //设置单词音标
        tvWordPhonetic.setText(info.getPhonetic());
        //设置单词的翻译
        tvWordExplan.setText(info.getText());
        //设置单词图片
        List<CloneWordPrepareInfo.DataBean.QuestionListBean.JpglistBean> jpglist = info.getJpglist();
        for (int i = 0; i < jpglist.size(); i++) {
            if (jpglist.get(i).getPicture().endsWith(info.getWordpic())) {
                ImageUtil.displayImage(this, ivPic, jpglist.get(i).getPicture());
            }
        }

        tvSentenceName.setText(info.getExample_t());
    }


    /**
     * 播放单词的录音
     */
    private void doPlayWordSounds() {
        //分别获取单词和句子的帧动画对象
        wordAnim = (AnimationDrawable) ivPlayWord.getDrawable();
        senceAnim = (AnimationDrawable) ivPlaySentence.getDrawable();


        //如果句子的动画正在执行,则停止句子的动画
        if (senceAnim.isRunning()) {
            senceAnim.stop();
            ivPlaySentence.setImageResource(R.drawable.st_voice_anim);
        }

        //如果自身的动画效果正在执行
        wordAnim.start();

        //改变底部播放录音按钮的状态
        ivPlayRecord.setImageResource(R.drawable.st_words_play_voice);

        MediaPlayerManager.getInstance().play(info.getSound(), new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                wordAnim.stop();
                ivPlayWord.setImageResource(R.drawable.st_voice_anim);
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                wordAnim.stop();
                ivPlayWord.setImageResource(R.drawable.st_voice_anim);
                return false;
            }
        });
    }


    /**
     * 播放句子的录音
     */
    private void doPlaySentenceSounds() {

        //分别获取单词和句子的帧动画对象
        wordAnim = (AnimationDrawable) ivPlayWord.getDrawable();
        senceAnim = (AnimationDrawable) ivPlaySentence.getDrawable();

        //如果句子的动画正在执行,则停止句子的动画
        if (wordAnim.isRunning()) {
            wordAnim.stop();
            ivPlayWord.setImageResource(R.drawable.st_voice_anim);
        }

        //如果自身的动画效果正在执行
        senceAnim.start();

        //改变底部播放录音按钮的状态
        ivPlayRecord.setImageResource(R.drawable.st_words_play_voice);

        MediaPlayerManager.getInstance().play(info.getExamplesound_t(), new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                //句子动画停止
                senceAnim.stop();
                //恢复默认值
                ivPlaySentence.setImageResource(R.drawable.st_voice_anim);
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                //句子动画停止
                senceAnim.stop();
                //恢复默认值
                ivPlaySentence.setImageResource(R.drawable.st_voice_anim);
                return false;
            }
        });
    }

    /**
     * 页面控件的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.rl_collection) {
            //收藏
            doCollectionAction(info);
        } else if (id == R.id.iv_play_word) {
            //播放单词音频
            doPlayWordSounds();
        } else if (id == R.id.iv_play_sentence) {
            //播放句子音频
            doPlaySentenceSounds();
        } else if (id == R.id.iv_play_record) {
            //播放录制的音频文件
            doBottomPlayAction();
        } else if (id == R.id.bt_next) {
            //单词的点击事件,跳转到词汇预习界面2
            Intent intent = new Intent(this, StudentVocabularyPrepareSecondActivity.class);

            //携带clone的数据集合过去
            intent.putExtra("questioninfos", GsonUtil.listToJson(data));

            //所有的单体点击进去都从给第一个开始学习
            intent.putExtra("currpos", currPos);

            //携带
            intent.putExtra(StudentVocabularyPrepareSecondActivity.LESSONID, lessonId);
            intent.putExtra(StudentVocabularyPrepareSecondActivity.GRADEID, gradeId);
            startActivity(intent);
            finish();
        }
    }


    /**
     * 做收藏和取消收藏的方法
     *
     * @param item
     */
    private void doCollectionAction(CloneWordPrepareInfo.DataBean.QuestionListBean item) {

        //收藏与取消收藏
        Map<String, String> map = new HashMap<>();
        if (item.getCollection() == 0) {
            map.put("type", "18");
        } else if (item.getCollection() == 1) {
            map.put("type", "19");
        }
        map.put("acc", AccountUtils.getAccount(this));//18062585082
        map.put("role", AccountUtils.getRole(this));
        map.put("gradeid", gradeId);
        map.put("lessonid", lessonId);
        map.put("moduleid", "10");
        map.put("typeid", item.getTitletype() + "");
        map.put("questionid", item.getTitle() + "");
        map.put("apptoken", AccountUtils.getToken(this));
//        Log.i("test", "token:" + AccountUtils.getToken(this));
        map.put("platform", "8");

        String url = "";

        //根据是否收藏的状态来标识请求接口
        if (item.getCollection() == 0) {
            //未收藏,请求收藏接口
            url = HttpAdress.COLLECTION;
        } else if (item.getCollection() == 1) {
            //已经收藏,请求取消收藏
            url = HttpAdress.CANCELCOLLECTION;
        }

        HttpUtils.post(url, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (item.getCollection() == 0) {
                    UiUtils.Toast("收藏失败," + BaseApplication.ERROR, false);
                } else if (item.getCollection() == 1) {
                    UiUtils.Toast("取消收藏失败," + BaseApplication.ERROR, false);
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (null != info) {
                        if ("200".equals(info.state)) {
                            if (item.getCollection() == 0) {
                                item.setCollection(1);
                                ivCollection.setImageResource(R.drawable.st_collection_has_select);
                                UiUtils.Toast("收藏成功", false);
                            } else if (item.getCollection() == 1) {
                                item.setCollection(0);
                                ivCollection.setImageResource(R.drawable.st_collection_normal);
                                UiUtils.Toast("取消收藏成功", false);
                            }
                            //发送消息通知题目展示界面的状态进行刷新操作
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(0x120);
                            busInfo.setPos(currPos);
                            EventBus.getDefault().post(busInfo);

                        } else {
                            if (item.getCollection() == 0) {
                                UiUtils.Toast("收藏失败," + "异常码:" + info.state, false);
                                Log.i("test", "异常码是:" + info.state);
                            } else if (item.getCollection() == 1) {
                                UiUtils.Toast("取消收藏失败," + "异常码:" + info.state, false);
                                Log.i("test", "异常码是:" + info.state);
                            }
                        }
                    }

                }
            }
        });
    }


    /**
     * 底部的播放按钮的点击事件
     * 播放录制的音频文件方法
     */
    private void doBottomPlayAction() {

        //获取录音的地址
        String saveAudioUrl = getAmrPath();
        LogUtils.iTag("test", "生成的录音文件地址是:" + saveAudioUrl);

        LogUtils.iTag("test", "文件是否存在:" + isExistRecordFile());

        // 根据音频地址判断是否有录音
//        if (!TextUtils.isEmpty(saveAudioUrl)) {
        if (isExistRecordFile()) {
            // 停止播放单词的动画
            if (wordAnim != null && wordAnim.isRunning()) {
                wordAnim.stop();
                ivPlayWord.setImageResource(R.drawable.st_voice_anim);
            }

            //停止播放句子的动画
            if (senceAnim != null && senceAnim.isRunning()) {
                senceAnim.stop();
                ivPlaySentence.setImageResource(R.drawable.st_voice_anim);
            }

            ivPlayRecord.setImageResource(R.drawable.st_words_pause_voice);

            //播放当前录制的音频
            MediaPlayerManager.getInstance().play(saveAudioUrl, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    ivPlayRecord.setImageResource(R.drawable.st_words_play_voice);
                }
            }, null);

        } else {
            // 无存放的音频文件
            UiUtils.Toast("请先录音", false);
            return;
        }
    }


    /**
     * 弹出录音的PopUpwindow
     */
    private void showRecordPop() {

        view = View.inflate(this, R.layout.st_pop_record, null);

        lvPopRecord = view.findViewById(R.id.lv_pop_record);

        // 给顶部的图片设置帧动画
        lvPopRecord.setImageResource(R.drawable.st_record_anim);

        // 获取帧动画对象
        popAnimationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();

        // 开启帧动画
        popAnimationDrawable.start();

        popupWindow = new PopupWindow(view,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                if (null != popAnimationDrawable) {
                    popAnimationDrawable.stop();
                }
            }
        });
        popupWindow.showAtLocation(this.getWindow().getDecorView(),
                Gravity.CENTER, 0, 0);
    }

    /**
     * 切换页面时停止播放录音
     */
    @Override
    protected void onDestroy() {
        //清空播放器
        MediaPlayerManager.getInstance().stop();
        //清除缓存文件
        deleteCurrRecord();
        super.onDestroy();
    }

    /**
     * 根据当前页面获取录音文件的路径的方法
     *
     * @return
     */
    private String getAmrPath() {
        //在内部存储中创建文件
//        File directory = getCacheDir();
//        String fileName = "app_record_" +
//                +currPos
//                + ".mp3";
//        //获取文件对象
//        File file = new File(directory, fileName);
//        return file.getAbsolutePath();


//        File file = new File(Environment.getExternalStorageDirectory()
//                .getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");

        File file = new File(getCacheDir()
                .getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");
        return file.getAbsolutePath();
    }

    /**
     * 清空当前缓存目录保存的录音文件
     */
    private void deleteCurrRecord() {
//        File directory = getCacheDir();
//        String fileName = "app_record_" +
//                +currPos
//                + ".mp3";
//        //获取文件对象
//        File file = new File(directory, fileName);

//        File file = new File(Environment.getExternalStorageDirectory()
//                .getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");

        File file = new File(getCacheDir()
                .getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 是否存在录音文件
     */
    private Boolean isExistRecordFile() {
//        File file = new File(Environment.getExternalStorageDirectory()
//                .getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");
        File file = new File(getCacheDir()
                .getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * ⑨重写onRequestPermissionsResult方法
     * 获取动态权限请求的结果,再开启录制音频
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // ToastUtils.showShort("录音权限开启,请重新进行录音操作");
            SnackbarUtil.ShortSnackbar(rlMain, "录音权限开启,请重新进行录音操作", 0).show();
        } else {
            // ToastUtils.showShort("您拒绝了录音权限,语音评测功能无法使用");
            SnackbarUtil.ShortSnackbar(rlMain, "您拒绝了录音权限,语音评测功能无法使用", 0).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    //----------------------------------------------------科大讯飞语音评测部分--------------------------------------------------------------


    /**
     * 设置讯飞语音录制对象的参数方法
     */
    private void setParams() {

        mSpeechEvaluator = SpeechEvaluator.createEvaluator(this, null);

        // 设置评测语种
        mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");

        // 设置评测题型
        // mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
        // "read_word");//单词

        mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
                "read_sentence");// 句子

        // 设置试题编码类型
        mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");

        // 设置前、后端点超时
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "3000");
        mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");

        // 设置录音超时，设置成-1 则无超时限制
        mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");

        // 设置结果等级，不同等级对应不同的详细程度
        mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        // 配置录音文件存放的位置-这里需要再录音的时候单独设置位置
        // mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
        // Environment.getExternalStorageDirectory().getAbsolutePath()
        // + "/msc/" + "ice" + postion + ".wav");
//        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH, getCacheDir().getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");

    }


    /**
     * 科大讯飞的语音评测的方法
     */
    @SuppressLint("MissingPermission")
    private void doRecordAction() {

        // 清空播放器的播放状态
        MediaPlayerManager.getInstance().stop();

        // 清除播放单词的录音
        if (wordAnim != null) {
            wordAnim.stop();
            ivPlayRecord.setImageResource(R.drawable.st_voice_anim);
        }

        //清除播放句子的录音
        if (senceAnim != null) {
            senceAnim.stop();
            ivPlaySentence.setImageResource(R.drawable.st_voice_anim);
        }


        // 恢复底部的播放按钮的状态
        ivPlayRecord.setImageResource(R.drawable.st_words_play_voice);

        // 震动手机
        Vibrator vibrator = (Vibrator) getSystemService(
                Service.VIBRATOR_SERVICE);
        vibrator.vibrate(500);

        if (mSpeechEvaluator == null) {
            return;
        }

//     重新配置讯飞的录音存放位置
//        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
//                Environment.getExternalStorageDirectory().getAbsolutePath()
//                        + "/xb_app/" + "ice" + currPos + ".wav");
        mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH, getCacheDir().getAbsolutePath() + "/xb_app/" + "ice" + currPos + ".wav");

        //开启评测 "[word]\r\n" +
        mSpeechEvaluator.startEvaluating(info.getWordname(), null, new EvaluatorListener() {
            // volume音量值0~30，data音频数据
            @Override
            public void onVolumeChanged(int volume, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {

            }

            @Override
            public void onEndOfSpeech() {

            }

            // 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
            @Override
            public void onResult(EvaluatorResult result, boolean isLast) {

                if (isLast) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            StringBuilder builder = new StringBuilder();
                            builder.append(result.getResultString());

                            XmlResultParser resultParser = new XmlResultParser();
                            Result result1 = resultParser.parse(result
                                    .getResultString());

                            // 处理乱读的问题
                            if (!TextUtils.isEmpty(builder)) {
                                float a = result1.total_score;
                                float b = (float) (Math.round(a * 10)) / 10;

                                // 更改是否继续显示弹框的标识
//                                isShowDialog = false;

                                if (null != popupWindow
                                        && popupWindow.isShowing()) {
                                    popupWindow.dismiss();
                                }

                                llLoading.setVisibility(View.INVISIBLE);
                                tvScore.setVisibility(View.VISIBLE);
                                tvScore.setText(b + " 分");

                                // 播放科大讯飞的评分语音
                                int resId = -1;
                                if (b < 1.0) {
                                    resId = R.raw.musicrecord1;
                                } else if (b >= 1.0 && b < 2.0) {
                                    resId = R.raw.musicrecord2;
                                } else if (b >= 2.0 && b < 3.0) {
                                    resId = R.raw.musicrecord3;
                                } else if (b >= 3.0 && b < 4.0) {
                                    resId = R.raw.musicrecord4;
                                } else if (b >= 4.0 && b <= 5.0) {
                                    resId = R.raw.musicrecord5;
                                }

                                MediaPlayerManager.getInstance().playLocalFile(resId, null, null);

                            }
                        }
                    });

                }

            }

            @Override
            public void onError(SpeechError error) {

                // 更新是否显示PopUpWindow
//                isShowDialog = false;

                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }

                if (null != llLoading) {
                    llLoading.setVisibility(View.INVISIBLE);
                }

                if (null != tvScore) {
                    tvScore.setVisibility(View.INVISIBLE);
                }

                UiUtils.Toast("请重新录音", false);

                Log.d("test", error.getErrorCode() + "");
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });
    }


    //-----------------------------------------------------腾讯云语音评测部分----------------------------------------------------------------
    //腾讯云的语音评测对象
    private TAIOralEvaluation oral;

    //腾讯云的语音评测对象的参数
    private TAIOralEvaluationParam param;

    //保存录制的音频地址
    private String audioUrl;

    //录音参数
    private TAIRecorderParam recordParam;


    /**
     * 配置腾讯云的语音评测对象的参数
     */
    private void setTencentParams() {
        param = new TAIOralEvaluationParam();
        param.context = this;
        //一次批改唯一标识
        param.sessionId = UUID.randomUUID().toString();
        param.appId = Constants.appId;
        param.soeAppId = Constants.soeAppId;
        param.secretId = Constants.secretId;
        param.secretKey = Constants.secretKey;
        param.token = Constants.token;
        //传输方式ONCE和STREAM
        param.workMode = TAIOralEvaluationWorkMode.STREAM;
        //评测模式,单词WORD,句子SENTENCE,段落PARAGRAPH,FREE不收约束
        param.evalMode = TAIOralEvaluationEvalMode.SENTENCE;
        //是否存储音频文件
        param.storageMode = TAIOralEvaluationStorageMode.ENABLE;
        //数据格式（目前支持mp3）
        param.fileType = TAIOralEvaluationFileType.MP3;
        //语言类型
        param.serverType = TAIOralEvaluationServerType.ENGLISH;
        param.textMode = TAIOralEvaluationTextMode.NORMAL;
        //苛刻指数，取值为[1.0 - 4.0]范围内的浮点数，用于平滑不同年龄段的分数，1.0为小年龄段，4.0为最高年龄段
        param.scoreCoeff = Double.parseDouble("1.0");
        //新版本的添加参数音频存储方案
//        param.audioPath = getAmrPath();

        //被评估语音对应的文本
        param.refText = info.getWordname();
        if (param.workMode == TAIOralEvaluationWorkMode.STREAM) {
            param.timeout = 5;
            param.retryTimes = 5;
        } else {
            param.timeout = 30;
            param.retryTimes = 0;
        }

        //录音参数配置
        recordParam = new TAIRecorderParam();
        recordParam.fragSize = (int) (Double.parseDouble("1.0") * 1024);
        recordParam.fragEnable = true;
        recordParam.vadEnable = true;
        recordParam.vadInterval = 4000;
    }


    /**
     * 腾讯云评测的方法
     */
    private void doTencenRecordAction() {

        // 清空播放器的播放状态
        MediaPlayerManager.getInstance().stop();

        // 清除播放单词的录音
        if (wordAnim != null) {
            wordAnim.stop();
            ivPlayRecord.setImageResource(R.drawable.st_voice_anim);
        }

        //清除播放句子的录音
        if (senceAnim != null) {
            senceAnim.stop();
            ivPlaySentence.setImageResource(R.drawable.st_voice_anim);
        }


        // 恢复底部的播放按钮的状态
        ivPlayRecord.setImageResource(R.drawable.st_words_play_voice);

        // 震动手机
        Vibrator vibrator = (Vibrator) getSystemService(
                Service.VIBRATOR_SERVICE);
        vibrator.vibrate(500);

        //创建评测对象
        if (oral != null) {
            //先清空评测对象
            oral = null;
        }

        //在创建一个新的评测对象
        oral = new TAIOralEvaluation();

        //设置录音参数
        setTencentParams();

        //录音配置
        oral.setRecorderParam(recordParam);

//-------------------------- 新版方法 -------------------------------------------
//        oral.setListener(new TAIOralEvaluationListener() {
//            @Override
//            public void onEvaluationData(TAIOralEvaluationData data, TAIOralEvaluationRet result) {
//                //记录得分
//                double score = 0.0;
////                if (2 == error.code) {
////                    //未录音
////                    audioUrl = "";
////                } else
////                    if ( data.bEnd == true && null != result) {
//
//                if (null != result) {
//
//                    //检测到录音
//                    LogUtils.iTag("test", "评测结果是:" + GsonUtil.objectToJson(result));
//
//                    //记录音频文件
//                    audioUrl = result.audioUrl;
//
//                    //详细发音评估结果
////                        List<TAIOralEvaluationWord> words = result.words;
//
//                    //发音精准度
//                    double pronAccuracy = result.pronAccuracy;
//
//                    //发音流利度
//                    double pronFluency = result.pronFluency;
//
//                    //发音完整度
//                    double pronCompletion = result.pronCompletion;
//
//                    //评分方式为建议评分 = 准确度（PronAccuracyfloat）× 完整度（PronCompletionfloat）×（2 - 完整度（PronCompletionfloat））
//
//                    //判断是否是乱读
//                    if (pronAccuracy <= 0 || pronFluency <= 0 || pronCompletion <= 0) {
//                        //乱读
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                audioUrl = "";
//                                UiUtils.Toast("检测到未录音或者乱读,请重新录音", false);
//                                llLoading.setVisibility(View.INVISIBLE);
//                                tvScore.setVisibility(View.INVISIBLE);
//                                tvScore.setText("0.0 分");
//                            }
//                        });
//
//                    } else {
//                        //不是乱读
//                        if (pronFluency >= 0.8) {
//                            score = pronAccuracy * pronCompletion * pronFluency;
//                        } else {
//                            score = pronAccuracy * pronCompletion;
//                        }
//
//                        //根据分数来播放语音
//                        int resId = -1;
//                        if (score < 20.0) {
//                            resId = R.raw.musicrecord1;
//                        } else if (score >= 20.0 && score < 40.0) {
//                            resId = R.raw.musicrecord2;
//                        } else if (score >= 40.0 && score < 60.0) {
//                            resId = R.raw.musicrecord3;
//                        } else if (score >= 60.0 && score < 80.0) {
//                            resId = R.raw.musicrecord4;
//                        } else if (score >= 80.0 && score <= 100.0) {
//                            resId = R.raw.musicrecord5;
//                        }
//                        LogUtils.iTag("test", "评测分数是:" + score);
//
//                        MediaPlayerManager.getInstance().playLocalFile(resId, null, null);
//
//                        //给分数赋值
//                        NumberFormat nf = new DecimalFormat("0.0 ");
//                        double resScore = Double.parseDouble(nf.format(score));
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                //显示评分并播放录音
//                                llLoading.setVisibility(View.INVISIBLE);
//                                tvScore.setVisibility(View.VISIBLE);
//                                tvScore.setText(resScore + " 分");
//                            }
//                        });
//
//                    }
//                }
//            }
//
//            @Override
//            public void onEvaluationError(TAIOralEvaluationData data, TAIError error) {
//
//            }
//
//            @Override
//            public void onFinalEvaluationData(TAIOralEvaluationData data, TAIOralEvaluationRet result) {
//
//            }
//
//            @Override
//            public void onEndOfSpeech(boolean isSpeak) {
//                // 检测到静音回调
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        UiUtils.Toast("检测到您未录音", false);
//                        llLoading.setVisibility(View.INVISIBLE);
//                        tvScore.setVisibility(View.INVISIBLE);
//                        tvScore.setText("0.0 分");
//                    }
//                });
//
//            }
//
//            @Override
//            public void onVolumeChanged(int volume) {
//                // 音频发生变化回调
//            }
//        });


//        ---------------------老版方法-------------------------------- -
        oral.startRecordAndEvaluation(param, new TAIOralEvaluationCallback() {
            @Override
            public void onResult(final TAIError error) {
            }
        });

        oral.setListener(new TAIOralEvaluationListener() {
            @Override
            public void onEvaluationData(final TAIOralEvaluationData data, final TAIOralEvaluationRet result, final TAIError error) {


                //记录得分
                double score = 0.0;

                if (2 == error.code) {
                    //未录音
                    audioUrl = "";

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UiUtils.Toast("检测到您未录音", false);
                            llLoading.setVisibility(View.INVISIBLE);
                            tvScore.setVisibility(View.INVISIBLE);
                            tvScore.setText("0.0 分");
                        }
                    });

                } else if (0 == error.code && data.bEnd == true && null != result) {

                    LogUtils.iTag("test", data);

                    //检测到录音
                    LogUtils.iTag("test", "评测结果是:" + GsonUtil.objectToJson(result));

                    //记录音频文件
                    audioUrl = result.audioUrl;

                    //详细发音评估结果
                    List<TAIOralEvaluationWord> words = result.words;

                    //发音精准度
                    double pronAccuracy = result.pronAccuracy;

                    //发音流利度
                    double pronFluency = result.pronFluency;

                    //发音完整度
                    double pronCompletion = result.pronCompletion;

                    //评分方式为建议评分 = 准确度（PronAccuracyfloat）× 完整度（PronCompletionfloat）×（2 - 完整度（PronCompletionfloat））

                    //判断是否是乱读
                    if (pronAccuracy <= 0 || pronFluency <= 0 || pronCompletion <= 0) {
                        //乱读
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                audioUrl = "";
                                UiUtils.Toast("检测到未录音或者乱读,请重新录音", false);
                                llLoading.setVisibility(View.INVISIBLE);
                                tvScore.setVisibility(View.INVISIBLE);
                                tvScore.setText("0.0 分");
                            }
                        });

                    } else {
                        //不是乱读
                        if (pronFluency >= 0.8) {
                            score = pronAccuracy * pronCompletion * pronFluency;
                        } else {
                            score = pronAccuracy * pronCompletion;
                        }

                        //根据分数来播放语音
                        int resId = -1;
                        if (score < 20.0) {
                            resId = R.raw.musicrecord1;
                        } else if (score >= 20.0 && score < 40.0) {
                            resId = R.raw.musicrecord2;
                        } else if (score >= 40.0 && score < 60.0) {
                            resId = R.raw.musicrecord3;
                        } else if (score >= 60.0 && score < 80.0) {
                            resId = R.raw.musicrecord4;
                        } else if (score >= 80.0 && score <= 100.0) {
                            resId = R.raw.musicrecord5;
                        }
                        LogUtils.iTag("test", "评测分数是:" + score);

                        MediaPlayerManager.getInstance().playLocalFile(resId, null, null);

                        //给分数赋值
                        NumberFormat nf = new DecimalFormat("0.0 ");
                        double resScore = Double.parseDouble(nf.format(score));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //显示评分并播放录音
                                llLoading.setVisibility(View.INVISIBLE);
                                tvScore.setVisibility(View.VISIBLE);
                                tvScore.setText(resScore + " 分");
                            }
                        });

                    }

                }

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onVolumeChanged(final int volume) {
            }
        });
    }
}
